package com.sys.common.controller;

import com.alibaba.fastjson.JSONObject;
import com.sys.common.pojo.ApiResponse;
import com.sys.common.pojo.ApiResponseEnum;
import com.sys.common.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 所有Controller的父类
 * @author 朱明宇
 */
public class BaseController
{
	@Resource
	protected DateFormatUtil dateFormatUtil;
	@Resource
	protected EncryptUtil encryptUtil ;
	@Resource
	protected FileUtil fileUtil ;
	protected ApiResponse<Object> infoResponse = new ApiResponse<Object>();
	
	/* 上传文件的jsp路径 */
	protected String uploadFile = "uploadFile" ;
	protected String updateFlag ; 
	/* true:表示清空页面信息 */
	protected String cleanInfoFlag = "true" ; 
	
	/**
	 * 页面上提示信息
	 */
	protected String info = ConstatFinalUtil.INFO_JSON.getString(ApiResponseEnum.STATUS_FAILED.getName()) ;
	
	/**
	 * 公共的一些操作
	 * @param currentPage
	 * @param pageSize
	 * @return
	 */
	protected void commonOper(HttpServletRequest request)
	{
		/* 存储一些公共的变量 */
		request.setAttribute("websiteUrl", ConstatFinalUtil.CONFIG_JSON.get("website.url"));
		request.setAttribute("websiteFileUrl", ConstatFinalUtil.CONFIG_JSON.get("website.fileUrl"));
		request.setAttribute("websiteHeadUrl", ConstatFinalUtil.CONFIG_JSON.get("website.head.url"));
		/* 存储系统配置表中的所有变量 */
		request.setAttribute("sys_pro_map", ConstatFinalUtil.SYS_PRO_MAP);
		/* 从数据库中读取一些变量 */
		request.setAttribute("sys_map", ConstatFinalUtil.SYS_PRO_MAP);
	}
	
	/**
	 * 生成分页对象
	 * @param currentPage
	 * @param pageSize
	 * @return
	 */
	protected PageInfoUtil proccedPageInfo(String currentPage, String pageSize)
	{
		/* 分页 */
		PageInfoUtil pageInfoUtil = new PageInfoUtil() ; 
		try
		{
			/* 将字符串转换成整数,有风险,
			 * 字符串为a,转换不成不整数
			 *  */
			pageInfoUtil.setCurrentPage(Integer.valueOf(currentPage));
			pageInfoUtil.setPageSize(Integer.valueOf(pageSize));
		} catch (NumberFormatException e)
		{
		}
		return pageInfoUtil;
	}
	
	/**
	 * 生成一个查询列表公共的搜索条件
	 * @param request
	 * @return
	 */
	protected  Map<String, Object> proccedSearch(HttpServletRequest request)
	{
		Map<String, Object> condMap = new HashMap<String, Object>();
		String keyword = request.getParameter("keyword");
		String status = request.getParameter("status");
		String st = request.getParameter("st");
		String ed = request.getParameter("ed");
		/* 将查询条件存储到request中 */
		request.setAttribute("keyword", keyword);		
		request.setAttribute("status", status);
		request.setAttribute("st", st);
		request.setAttribute("ed", ed);
		/* 关键字 */
		if(keyword == null)
		{
			keyword = "" ; 
		}
		
		/* 状态 */
		if(status == null)
		{
			status = "" ; 
		}
		
		/* 查询的起始时间和结束时间 */
		Date stDate = null ; 
		Date edDate = null ;
		if(st != null && !"".equalsIgnoreCase(st) && ed != null && !"".equalsIgnoreCase(ed))
		{
			stDate = this.dateFormatUtil.strDateTime(st);
			edDate = this.dateFormatUtil.strDateTime(ed);
		}
		condMap.put("keyword", keyword);		
		condMap.put("status", status);
		condMap.put("stDate", stDate);
		condMap.put("edDate", edDate);
		return condMap;
	}
	
	/**
	 * 生成分页对象
	 * @param currentPage
	 * @param pageSize
	 * @return
	 */
	protected PageInfoUtil proccedPageInfo(HttpServletRequest request)
	{
		String currentPage = request.getParameter("currentPage");
		String pageSize = request.getParameter("pageSize");
		/* 分页 */
		PageInfoUtil pageInfoUtil = new PageInfoUtil() ; 
		try
		{
			/* 将字符串转换成整数,有风险,
			 * 字符串为a,转换不成不整数
			 *  */
			pageInfoUtil.setCurrentPage(Integer.valueOf(currentPage));
			pageInfoUtil.setPageSize(Integer.valueOf(pageSize));
		} catch (NumberFormatException e)
		{
		}
		return pageInfoUtil;
	}
	
	/**
	 * 从session中获取用户或者管理员信息
	 * @return
	 */
	protected Object findObjfromSession(HttpServletRequest request , String type)
	{
		HttpSession session = request.getSession();
		if("users".equalsIgnoreCase(type))
		{
			return session.getAttribute("users");
		}else if("admins".equalsIgnoreCase(type))
		{
			return session.getAttribute("admins");
		}
		return null ; 
	}
	
	/**
	 * 返回json字符串
	 * @param request
	 * @param info
	 * @return
	 * @throws IOException 
	 */
	public JSONObject printOut(HttpServletRequest request , HttpServletResponse response , String returnStr)
	{
		try
		{
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter out = response.getWriter();
			out.print(returnStr);
			out.flush();
			out.close();
		} catch (IOException e)
		{
			ConstatFinalUtil.SYS_LOGGER.error("为客户端返回信息出错了;" , e);
		}
		return null; 
	}
	
	/**
	 * 获取真实的Ip
	 * @return
	 */
	protected String findIp(HttpServletRequest request)
	{
		String ip = "";
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
		{
			ip = request.getHeader("x-real-ip");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
		{
			ip = request.getHeader("x-forwarded-for");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
		{
			ip = request.getHeader("proxy-client-ip");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
		{
			ip = request.getHeader("wl-proxy-client-ip");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
		{
			ip = request.getHeader("http-client-ip");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
		{
			ip = request.getRemoteAddr();
		}
		/* 去掉IP中的端口 */
		String strIndex = ":" ;
		if(ip.indexOf(strIndex) != -1)
		{
			/* 从0截取到最后一个:的位置 */
			ip = ip.substring(0, ip.lastIndexOf(strIndex));
		}
		return ip;
	}
	
	/**
	 * 获取原来的状态信息
	 * @param request
	 * @param apiResponse
	 */
	protected JSONObject souResponse(HttpServletRequest request, JSONObject paramJSON)
	{
		/* 如果原来的状态有信息,直接更新 */
		JSONObject responseJSON = (JSONObject) request.getAttribute("response");
		if(responseJSON != null)
		{
			paramJSON.put("code", responseJSON.getInteger("code"));
			paramJSON.put("info", responseJSON.getString("info"));
		}
		return paramJSON ; 
	}
	
	/**
	 * 验证 验证码输入的是否正确
	 * @param request
	 * @param apiResponse
	 */
	protected ApiResponse<Object> verifyCode(HttpServletRequest request)
	{
		ApiResponse<Object> apiResponse = new ApiResponse<>();
		/* 默认肯定是错误 */
		HttpSession session = request.getSession() ; 
		String randSess = (String) session.getAttribute("randSess");
		String code = request.getParameter("code");
		if(randSess != null && randSess.equalsIgnoreCase(code))
		{
			/* 验证码正确 */
			apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
		}else
		{
			/* 验证码不正确 */
			apiResponse.setCode(ApiResponseEnum.INFO_VERIFY_CODE_INCORR.getStatus());
		}
		
		apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
		request.setAttribute("response", apiResponse.toJSON());
		/* 移除验证码 */
		session.removeAttribute("randSess");
		return apiResponse ; 
	}
}
